<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\bootstrap\Progress;
use frontend\modules\common\models\BaseParam;

use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $model common\models\Banner */
/* @var $form yii\widgets\ActiveForm */
?>
<style>
    .add_upload {
        overflow: hidden;
        padding: 10px 15px;

        position: relative;
        border: 1px solid #DFDFDF;
        transition: border 0.2s;
        -moz-transition: border 0.2s;
        -webkit-transition: border 0.2s;
        -o-transition: border 0.2s;
        text-align: center;
        vertical-align: middle;
    }

    #uploadImg {
        float: left;
        overflow: hidden;
    }

    #uploadImg img {
        border: none;
        max-width: 300px;
        height: auto;
    }

    #banner-img_url,#banner-img_url {
        height: 0;
        opacity: 0;
    }
</style>
<div class="banner-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'ba_name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'ba_url_pc')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'ba_url_mini')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'ba_sort')->textInput() ?>

    <?= $form->field($model, 'br_id')->dropDownList($branchInfo) ?>

    <?= $form->field($model, 'status')->textInput()->dropDownList(BaseParam::$bannerStatus) ?>

    <?= $form->field($model, 'img_url', [
        'options' => ['class' => 'banner-img_url'],
        //'inputOptions' => ['type' => 'hidden'],
    ])->fileInput(); ?>
    <?= Progress::widget(['barOptions' => ['class' => 'progress-bar-success'], 'options' => ['class' => 'active progress-striped', 'style' => 'display:none']]) ?>
    <label for="banner-img_url" style="display: block">
        <div class="add_upload">
            <div id="uploadImg">
                <img class="upload_image" src="../../images/add_img.png">
            </div>
        </div>
    </label>

    <div class="form-group">
        <?= Html::submitButton('确认', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
<script>
    <?php $this->beginBlock('js_upload') ?>
    $(document).ready(function () {
        <?php if(empty($model->img_url)):?>
        var pic_val = '';
        <?php else:?>
        var pic_val = '<?= $model->img_url ?>';
        <?php endif?>

        var imgUrl =  '<?=BaseParam::$imgUrl?>';
        console.log(pic_val);
        if (pic_val) {
            $(".field-banner-img_url").find('input').first().val(pic_val);
            $('#uploadImg').find('img').attr('src', imgUrl+pic_val);
        }
    });

    $(document).on('click', '.s-btn', function () {
        var pic_val = $(".field-banner-img_url").find('input').first().val();
        if (pic_val == 'loading') return false;
    });
    $(document).on('change', '#banner-img_url', function () {
        console.log('上传');
        var img_file = $('#banner-img_url');
        var pic = $('#uploadImg')[0];
        var pro = $('#w1');
        var pic_val = $(".field-banner-img_url").find('input').first();
        setImagePreviews(img_file[0], pic);
        pic_val.val('loading');
        //进度条 显示
        pro.show();
        var fd = new FormData();
        fd.append('image', img_file[0].files[0]);

        $.ajax({
            url: "http://local.tdx.com/resource/banner/upload-img",
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            dataType: "json",
            xhr: function () {
                var myxhr = $.ajaxSettings.xhr();
                if (myxhr.upload) {
                    myxhr.upload.addEventListener("progress", function () {
                        uploadProgress(event, pro.find('.progress-bar-success'))
                    }, false);
                }
                return myxhr;
            },
            success: function (msg) {
                pic_val.val(msg.data);
                //进度条隐藏
                pro.hide().find('.progress-bar-success').css('height', '0');
            },
            error: function (xhr, textStatus) {
            }
        })
    });

    //展示图片
    function setImagePreviews(docObj, dd) {
        dd.innerHTML = "";
        var fileList = docObj.files;
        for (var i = 0; i < fileList.length; i++) {
            dd.innerHTML += "<div style='float:left' > <img id='img" + i + "'  /> </div>";
            var imgObjPreview = document.getElementById("img" + i);
            if (docObj.files && docObj.files[i]) {
                //火狐下，直接设img属性
                imgObjPreview.style.display = 'block';
                //imgObjPreview.src = docObj.files[0].getAsDataURL();
                //火狐7以上版本不能用上面的getAsDataURL()方式获取，需要一下方式
                imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]);
            }
            else {
                //IE下，使用滤镜
                docObj.select();
                var imgSrc = document.selection.createRange().text;
                var localImagId = document.getElementById("img" + i);
                //必须设置初始大小
                localImagId.style.width = "150px";
                localImagId.style.height = "180px";
                //图片异常的捕捉，防止用户修改后缀来伪造图片
                try {
                    localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                }
                catch (e) {
                    alert("您上传的图片格式不正确，请重新选择!");
                    return false;
                }
                imgObjPreview.style.display = 'none';
                document.selection.empty();
            }
        }
        return true;
    }

    function uploadProgress(evt, progress) {
        if (evt.lengthComputable) {
            //evt.loaded：文件上传的大小 evt.total：文件总的大小
            var percentComplete = Math.round((evt.loaded) * 100 / evt.total);
            progress.animate({width: percentComplete + '%'}, 100);
        }
    }
    <?php $this->endBlock() ?>
</script>
<?php $this->registerJs($this->blocks['js_upload']); ?>
